package com.sgj.service.impl;

import com.sgj.dao.TypeRepository;
import com.sgj.exception.NotFoundExcepiton;
import com.sgj.pojo.Type;
import com.sgj.service.TypeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * @author 沈国纪
 * @date 2021/3/30 17:16
 */
@Service
public class TypeServiceImpl implements TypeService {

	@Autowired
	private TypeRepository typeRepository;

	/**
	 * 新增分类
	 * @param type
	 * @return
	 */
	@Transactional
	@Override
	public Type saveType(Type type) {
		return typeRepository.save(type);
	}

	/**
	 * 根据名称查询分类
	 * @param name
	 * @return
	 */
	@Override
	public Type findTypeByName(String name) {
		return typeRepository.findByName(name);
	}

	/**
	 * 根据 id 查询分类
	 * @param id
	 * @return
	 */
	@Transactional
	@Override
	public Type findTypeById(Long id) {
		return typeRepository.getOne(id);
	}

	/**
	 * 分页查询
	 * @param pageable
	 * @return
	 */
	@Transactional
	@Override
	public Page<Type> listType(Pageable pageable) {
		return typeRepository.findAll(pageable);
	}

	/**
	 * 查询返回列表
	 * @return
	 */
	@Transactional
	@Override
	public List<Type> listType() {
		return typeRepository.findAll();
	}

	/**
	 * 主页分类查询
	 * @param size
	 * @return
	 */
	@Override
	public List<Type> listTypeTop(Integer size) {
		Sort sort = Sort.by(Sort.Direction.DESC, "blogs.size");
		Pageable pageable = PageRequest.of(0, size, sort);
		return typeRepository.findTop(pageable);
	}

	/**
	 * 修改分类
	 * @param type
	 * @return
	 */
	@Transactional
	@Override
	public Type updateType(Type type) {
		Type t = typeRepository.getOne(type.getId());
		if (Objects.isNull(t)) {
			throw new NotFoundExcepiton("不存在该类型");
		}
		BeanUtils.copyProperties(type, t);
		return typeRepository.save(t);
	}

	/**
	 * 根据 id 删除分类
	 * @param id
	 * @return
	 */
	@Transactional
	@Override
	public void deleteType(Long id) {
		typeRepository.deleteById(id);
	}
}
